package com.api.projects.service.impl;

import com.api.apicommon.model.entity.UserInterfaceInfo;
import com.api.projects.common.ErrorCode;
import com.api.projects.exception.BusinessException;
import com.api.projects.mapper.UserInterfaceInfoMapper;
import com.api.projects.service.UserInterfaceInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 用户接口信息服务
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService{

    //剩余调用次数
    private final static Integer RESIDUE_INVOKE_NUM = 10;
    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if(userInterfaceInfo == null || userInterfaceInfo.getUserid() == null || userInterfaceInfo.getInterfaceinfoid() == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //userInterafceInfo表里的信息只有interfaceId 和  userid
        QueryWrapper<UserInterfaceInfo> query = new QueryWrapper<>();
        query.eq("userId",userInterfaceInfo.getUserid());
        query.eq("interfaceInfoId",userInterfaceInfo.getInterfaceinfoid());
        //得到用户接口信息
        UserInterfaceInfo newUserInterfaceInfo = this.baseMapper.selectOne(query);
        if(newUserInterfaceInfo == null){
            //设置剩余调用次数
            userInterfaceInfo.setLeftnum(10);
            //说明不存在，则需要自己进行用户接口信息的初始化
            int insert = this.baseMapper.insert(userInterfaceInfo);
            if(insert < 1){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据连接失败");
            }
        }else {
            //检查剩余调用次数
            Integer leftnum = newUserInterfaceInfo.getLeftnum();
            if (leftnum == null || leftnum <= 0) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "剩余调用次数不足");
            }
        }
    }

    /**
     * 因为在调用的时候已经校验了调用次数，说明这里是可以直接调用的
     * @param interfaceInfoId   接口Id
     * @param userId 用户Id
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId",interfaceInfoId);
        updateWrapper.eq("userId",userId);
        updateWrapper.setSql("leftNum = leftNum - 1 , totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }
}
